var db = require("../dao/db");

const sql = `select t.id, t.username, t.tel, t.create_time,
                      (select count(id) from user_tel t2 where t2.username = t.username ) buy_num,
                      (select t2.create_time from user_tel t2 where t2.username = t.username order by t2.create_time asc limit 1 ) buy_time,
                rank()over(partition by t.username order by t.create_time) buy_order
               from user_tel t
    `;
function queryList(params) {
    return new Promise((resolve, reject)=>{
        db.query(sql, function (err,rows) {
            if(err){
                console.log('queryList数据出错：', err)
                return reject('程序异常');
            }
            return resolve(rows);
        });
    })
}


function queryByPage(params) {
    return new Promise((resolve, reject)=>{
        db.queryByPage(sql,params,  function (err,rows) {
            if(err){
                console.log('queryByPage数据出错：', err)
                return reject('程序异常');
            }
            return resolve(rows);
        });
    })
}


function queryCount(params) {
    return new Promise((resolve, reject)=>{
        db.queryCount(sql,params,  function (err,rows) {
            if(err){
                console.log('queryCount数据出错：', err)
                return reject('程序异常');
            }
            return resolve(rows[0].count);
        });
    })
}



function queryById(id) {
    return new Promise((resolve, reject)=>{
        db.query(`select * from user_tel where id = ? `,[id],  function (err,rows) {
            if(err){
                console.log('queryById数据出错：', err)
                return reject('程序异常');
            }
            return resolve(rows);
        });
    })
}

function update(vo) {
    return new Promise((resolve, reject)=>{
        db.query(`update user_tel set username = ? where id = ?`,[vo.username, vo.id],  function (err,rows) {
            if(err){
                console.log('update数据出错：', err)
                return reject('程序异常');
            }
            return resolve(rows);
        });
    })
}


exports.queryList = queryList;
exports.queryByPage = queryByPage;
exports.queryCount = queryCount;
exports.queryById = queryById;
exports.update = update;